package com.mysteel.monitor.controller;

import com.mysteel.monitor.core.annotation.Monitor;
import com.mysteel.monitor.core.annotation.MonitorMethod;
import com.mysteel.monitor.core.jstat.Jstat;
import com.mysteel.monitor.core.jstat.model.StatModel;
import com.mysteel.monitor.core.response.RespResult;
import com.mysteel.monitor.core.utils.PidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 *  统计监测工具
 * @author:admin
 * @link https://www.cnblogs.com/sxdcgaq8080/p/11089841.html
 */
@Monitor("/v1/api/stat")
public class StatController {

    private static  final Logger logger = LoggerFactory.getLogger(StatController.class);
    private static  final List<String> validCommnads  = Arrays.asList("class",
            "compiler","gc","gccapacity","gcnew","gcnewcapacity","gcold","gcoldcapacity",
            "gcpermcapacity","gcmetacapacity","gcutil","printcompilation");
    /**
     *  //    类加载统计 jstat -class 19570
     * //    编译统计 jstat -compiler 19570
     * //    垃圾回收统计 jstat -gc 19570
     * //    堆内存统计 jstat -gccapacity 19570
     * //    新生代垃圾回收统计 jstat -gcnew 19570
     * //    新生代内存统计 jstat -gcnewcapacity 19570
     * //    老年代垃圾回收统计 jstat -gcold 19570
     * //    老年代内存统计 jstat -gcoldcapacity 19570
     * //    永久代空间统计 jstat -gcpermcapacity 19570
     * //    元数据空间统计 jstat -gcmetacapacity 7172
     * //    总结垃圾回收统计 jstat -gcutil 19570
     * //    编译方法统计 jstat -printcompilation 19570
     * @return
     */

    @MonitorMethod("command")
    public RespResult<StatModel> doCommand(HttpServletRequest request) {
        boolean isContainHeader = Boolean.parseBoolean(request.getParameter("isContainHeader"));
        String command = request.getParameter("command");
        StatModel statModel = new StatModel();
        try {
            Thread.sleep(2000);
            statModel.setContainHeader(isContainHeader);
            statModel.setCommand(command);
            // 执行监控命令
            Jstat.excute(new String[]{"-" + command, PidUtils.currentPid()}, statModel);
        }catch (Exception e){
            logger.error("isContainHeader ={} ,command = {}",isContainHeader,command,e);
        }
        // 返回操作结果
        return  RespResult.success(statModel);
    }



}
